from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
uri = "mysql+pymysql://root:123456@localhost:3306/future"
app.config['SQLALCHEMY_DATABASE_URI'] = uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Car(db.Model):
    __tablename__ = 'car'
    number = db.Column(db.String(7), primary_key=True)
    type = db.Column(db.String(16))
    color = db.Column(db.String(8))
    brand = db.Column(db.String(8))
    price = db.Column(db.Float)
    description = db.Column(db.String(255))

@app.route('/index')
def index():
    db.drop_all()
    db.create_all()
    car1 = Car(number='京A88888', type='商务车', color='白色', brand='宝马', price=100000, description='超级豪华车')
    car2 = Car(number='京A88889', type='商务车', color='白色', brand='宝马', price=100000, description='超级豪华车')
    car3 = Car(number='京A88890', type='商务车', color='白色', brand='宝马', price=100000, description='超级豪华车')
    db.session.add(car1)
    db.session.add(car2)
    db.session.add(car3)
    db.session.commit()

    return render_template("Caradd.html")

@app.route('/add', methods=['POST'])
def add():
        number = request.form.get('number')
        type = request.form.get('type')
        color = request.form.get('color')
        brand = request.form.get('brand')
        price = request.form.get('price')
        description = request.form.get('description')
        try:
            car = Car(number=number, type=type, color=color, brand=brand, price=price, description=description)
            db.session.add(car)
            db.session.commit()
            return '添加成功'
        except Exception as e:
            return f'添加失败,失败原因是{e}'

@app.route('/delete', methods=['POST'])
def delete():
    number = request.form.get('number')
    try:
        car = Car.query.filter_by(number=number).first()
        db.session.delete(car)
        db.session.commit()
        return '删除成功'
    except Exception as e:
        return f'删除失败,失败原因是{e}'
@app.route('/update', methods=['POST'])
def update():
    number = request.form.get('number')
    type = request.form.get('type')
    color = request.form.get('color')
    brand = request.form.get('brand')
    price = request.form.get('price')
    description = request.form.get('description')
    try:
        car = Car.query.filter_by(number=number).first()
        car.type = type
        car.color = color
        car.brand = brand
        car.price =price
        car.description = description
        db.session.commit()
        return '修改成功'
    except Exception as e:
        return f'修改失败,失败原因是{e}'
@app.route('/list',methods=['GET'])
def list():
    cars = Car.query.all()
    names = []
    for u in cars:
        names.append(u.number)
    r = ','.join(names)
    return f"查询成功，当前系统车辆有{r}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8001, debug=True)
